using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Book.Blog.Core.DTOs;
using Book.Blog.Core.Interfaces;

namespace Book.Blog.API.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class SettingsController : ControllerBase
    {
        private readonly ISettingService _settingService;

        public SettingsController(ISettingService settingService)
        {
            _settingService = settingService;
        }

        /// <summary>
        /// 获取所有设置（需管理员）
        /// </summary>
        /// <returns>设置列表</returns>
        [HttpGet]
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> GetAllSettings()
        {
            var settings = await _settingService.GetAllSettingsAsync();
            return Ok(settings);
        }

        /// <summary>
        /// 获取公开设置
        /// </summary>
        /// <returns>公开设置</returns>
        [HttpGet("public")]
        public async Task<IActionResult> GetPublicSettings()
        {
            var settings = await _settingService.GetPublicSettingsAsync();
            return Ok(settings);
        }

        /// <summary>
        /// 获取设置分组（需管理员）
        /// </summary>
        /// <returns>设置分组</returns>
        [HttpGet("groups")]
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> GetSettingGroups()
        {
            var groups = await _settingService.GetSettingGroupsAsync();
            return Ok(groups);
        }

        /// <summary>
        /// 获取站点设置
        /// </summary>
        /// <returns>站点设置</returns>
        [HttpGet("site")]
        public async Task<IActionResult> GetSiteSettings()
        {
            var settings = await _settingService.GetSiteSettingsAsync();
            return Ok(settings);
        }

        /// <summary>
        /// 获取邮件设置（需管理员）
        /// </summary>
        /// <returns>邮件设置</returns>
        [HttpGet("email")]
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> GetEmailSettings()
        {
            var settings = await _settingService.GetEmailSettingsAsync();
            return Ok(settings);
        }

        /// <summary>
        /// 获取存储设置（需管理员）
        /// </summary>
        /// <returns>存储设置</returns>
        [HttpGet("storage")]
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> GetStorageSettings()
        {
            var settings = await _settingService.GetStorageSettingsAsync();
            return Ok(settings);
        }

        /// <summary>
        /// 创建设置（需管理员）
        /// </summary>
        /// <param name="dto">设置信息</param>
        /// <returns>新建设置</returns>
        /// <remarks>
        /// 示例请求:
        /// {
        ///   "key": "SiteTitle",
        ///   "value": "我的博客",
        ///   "group": "Site"
        /// }
        /// </remarks>
        [HttpPost]
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> CreateSetting([FromBody] CreateSettingDTO dto)
        {
            var setting = await _settingService.CreateSettingAsync(dto);
            return CreatedAtAction(nameof(GetSettingByKey), new { key = setting.Key }, setting);
        }

        /// <summary>
        /// 根据key获取设置
        /// </summary>
        /// <param name="key">设置key</param>
        /// <returns>设置详情</returns>
        [HttpGet("{key}")]
        public async Task<IActionResult> GetSettingByKey(string key)
        {
            var setting = await _settingService.GetSettingByKeyAsync(key);
            if (setting == null)
            {
                return NotFound();
            }
            return Ok(setting);
        }

        /// <summary>
        /// 更新设置（需管理员）
        /// </summary>
        /// <param name="key">设置key</param>
        /// <param name="dto">设置信息</param>
        /// <returns>更新后的设置</returns>
        /// <remarks>
        /// 示例请求:
        /// {
        ///   "key": "SiteTitle",
        ///   "value": "新标题",
        ///   "group": "Site"
        /// }
        /// </remarks>
        [HttpPut("{key}")]
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> UpdateSetting(string key, [FromBody] UpdateSettingDTO dto)
        {
            var setting = await _settingService.GetSettingByKeyAsync(key);
            if (setting == null)
            {
                return NotFound();
            }

            setting = await _settingService.UpdateSettingAsync(dto);
            return Ok(setting);
        }

        /// <summary>
        /// 批量更新设置（需管理员）
        /// </summary>
        /// <param name="dto">批量设置信息</param>
        /// <returns>操作结果</returns>
        /// <remarks>
        /// 示例请求:
        /// {
        ///   "settings": [
        ///     {"key": "SiteTitle", "value": "新标题"},
        ///     {"key": "SiteDescription", "value": "新描述"}
        ///   ]
        /// }
        /// </remarks>
        [HttpPost("batch")]
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> BatchUpdateSettings([FromBody] BatchUpdateSettingsDTO dto)
        {
            await _settingService.BatchUpdateSettingsAsync(dto);
            return Ok();
        }

        /// <summary>
        /// 删除设置（需管理员）
        /// </summary>
        /// <param name="key">设置key</param>
        /// <returns>无内容</returns>
        [HttpDelete("{key}")]
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> DeleteSetting(string key)
        {
            var setting = await _settingService.GetSettingByKeyAsync(key);
            if (setting == null)
            {
                return NotFound();
            }

            await _settingService.DeleteSettingAsync(setting.Id);
            return NoContent();
        }

        /// <summary>
        /// 重置为默认设置（需管理员）
        /// </summary>
        /// <returns>操作结果</returns>
        [HttpPost("reset")]
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> ResetToDefault()
        {
            await _settingService.ResetToDefaultAsync();
            return Ok();
        }

        /// <summary>
        /// 校验设置值（需管理员）
        /// </summary>
        /// <param name="key">设置key</param>
        /// <param name="value">设置值</param>
        /// <returns>校验结果</returns>
        [HttpPost("validate")]
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> ValidateSettingValue(
            [FromQuery] string key,
            [FromQuery] string value)
        {
            var isValid = await _settingService.ValidateSettingValueAsync(key, value);
            return Ok(new { IsValid = isValid });
        }
    }
} 